import XEUtils from "xe-utils";
import { message } from "ant-design-vue";
import settingApi from "@/api/common/setting-api";
import { storeHooks } from "@/store/modules/common";
import { generatorRoutes } from "@/router";
import {
  changePassword,
  empLogin,
  getUserInfo,
  getUserMarks,
} from "@/api/yuxin-main/user";
import { createPinia, defineStore } from "pinia";
// 数据持久化
import piniaPluginPersist from "pinia-plugin-persist";

const pinia = createPinia();
pinia.use(piniaPluginPersist);
export default pinia;

export const useStore = defineStore("main", {
  state: () => ({
    /** 所有权限 */
    permissions: <string[]>[],
    /**
     * 访问token
     */
    accessToken: null,
    refreshToken: null,
    lockVisible: false,
    enterprise: null,
    /**
     * 搜索容器是否渲染完成可见
     */
    searchVisible: true,
    /**
     * 当前登录用户
     */
    currentUser: <any>{},
    isFormWx: false,
    // 钱包用户信息
    walletMemberId: null,
    walletMemberInfo: {},
    //deptId
    deptOptionData: [],
  }),
  actions: {
    /**
     * 跳转至登录页
     * @param store
     */
    redirectLogin() {
      const shouldShowIcon = localStorage.getItem("shouldShowIcon") === "false";
      if (shouldShowIcon) {
        location.href = "/login?with_blank=1";
        localStorage.removeItem("shouldShowIcon");
      } else {
        location.href = "/login";
      }
    },
    setAccessToken(token: any) {
      this.accessToken = token;
    },
    setEnterprise(enterprise: any) {
      this.enterprise = enterprise;
    },
    /**
     * 登录
     * @param store
     * @param params
     */
    async userLogin(params: any) {
      const { loginState, token, menu } = params;
      this.accessToken = token;
      this.permissions = menu;

      this.setCurrentUser({
        name: String(loginState.mobile),
        phone: loginState.mobile,
      });

      // 生成路由
      this.generateMenus();

      // 重新登录不需要重定向
      if (params.type === "again") {
        return;
      }
      // 个人信息获取完毕后再跳转至首页
      location.href = "/";
    },
    async userLoginByToken(params: any) {},
    async userLogout() {
      await this.$reset();
      await this.redirectLogin();
    },
    async setCurrentUser(data) {
      this.currentUser = data;
    },
    async changePassword(params: any) {
      const { account, password, verifyCode, shopNo } = params;
      await changePassword({
        mobile: account,
        password,
        smsCode: verifyCode,
        shopNo,
      });
      message.success("密码修改成功,请重新登陆！");
      await this.userLogout();
    },
    generateMenus() {
      return generatorRoutes();
    },
    hasPermissions(value: any) {
      if (value) {
        const values = [value].flat();
        return this.permissions.some((permission: any) => {
          return values.includes(permission?.perms?.[0]);
        });
      } else {
        return true;
      }
    },
    async getDeptOptions() {
      console.log("chufa getDeptOptions");

      if (this.deptOptionData.length) return this.deptOptionData;
      const res = await Promise.all([
        settingApi.getDeptTreeList(),
        settingApi.getAllEmpList(),
      ]);
      this.setDeptOptions(res);
    },
    setDeptOptions(value: any) {
      if (value) {
        this.deptOptionData = value;
      }
    },
  },
  // 数据持久化设置
  persist: {
    enabled: true,
    strategies: [
      // localStorage存储
      { key: "YUXIN_PMS_STATE", storage: localStorage },
    ],
  },
});

storeHooks.setStore(useStore);
